#include "AbstractItemProxy.h"



#include <QDebug>
#include <QTimer>



AbstractItemProxy::AbstractItemProxy(QObject *parent) :
    QAbstractProxyModel(parent)
{
}


QModelIndex AbstractItemProxy::mapToSource(const QModelIndex &proxyIndex) const
{
    return m_indexMap.key(proxyIndex);
}


QModelIndex AbstractItemProxy::mapFromSource(const QModelIndex &sourceIndex) const
{
    return m_indexMap.value(sourceIndex);
}


QModelIndex AbstractItemProxy::index(int row, int column, const QModelIndex &proxyParent) const
{
    if (!hasIndex(row, column, proxyParent) || proxyParent.isValid()) return QModelIndex();

    QMapIterator<QPersistentModelIndex, QPersistentModelIndex> it(m_indexMap);

    while (it.hasNext())
    {
        it.next();
        if (it.value().row() != row ||
            it.value().column() != column) continue;

        return it.value();
    }

    return QModelIndex();
}


QModelIndex AbstractItemProxy::parent(const QModelIndex &proxyChild) const
{
    Q_UNUSED(proxyChild);

    return QModelIndex();
}


int AbstractItemProxy::rowCount(const QModelIndex &proxyParent) const
{
    if (proxyParent.isValid()) return 0;

    int rows = 0;
    QMapIterator<QPersistentModelIndex, QPersistentModelIndex> it(m_indexMap);

    int row = -1;
    while (it.hasNext())
    {
        it.next();
        if (it.value().row() > row) rows++;
        row = it.value().row();
    }

    return rows;
}


ItemModel* AbstractItemProxy::itemModel() const
{
    return dynamic_cast<ItemModel*>(sourceModel());
}

void AbstractItemProxy::setItemModel(ItemModel *model)
{
    setSourceModel(model);
}

QAbstractItemModel* AbstractItemProxy::sourceModel() const
{
    return QAbstractProxyModel::sourceModel();
}


void AbstractItemProxy::setSourceModel(QAbstractItemModel *sourceModel)
{
    QAbstractProxyModel::setSourceModel(sourceModel);
    QTimer::singleShot(0, this, SLOT(remap()));
}


